package u;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.imageio.stream.FileImageInputStream;

public abstract class Utils {

    public interface IExecutor {
        public void pre();
        public void exec(String line);
        public void post();
    }

    abstract static public class AbstractExecutor implements IExecutor{
        public void pre(){}
        public void exec(String line){}
        public void post(){}
    }
    
    /**
     * implement 
     * use  BufferedReader
     * 
     * @param file
     * @param executor
     * @return
     * @throws IOException
     */
    public static IExecutor readLine(File file, IExecutor executor)
            throws IOException {
        return readLine(new FileInputStream(file), executor);
    }

    public static IExecutor readLine(InputStream inputStream, IExecutor executor) throws IOException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        
        try {
            executor.pre();
            String line = null;
            while ((line = reader.readLine()) != null) {
                executor.exec(line);
            }

        } finally {
            try {
                reader.close();
            } finally {
                executor.post();
            }

        }

        return executor;
    }
    
    public static String getAtOnce(File file, String charaset) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        byte[] buf = new byte[8192];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int c = 0;
        try {
            while((c = bis.read(buf)) != -1) {
                baos.write(buf, 0, c);
                baos.flush();
            }    
        } finally {
            bis.close();
        }
        
        return new String(baos.toByteArray(), charaset);
    }

}
